<!DOCTYPE html>
<html lang="zh-cn">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width,initial-scale=1.0,maximum-scale=1.0,minimum-scale=1.0,user-scalable=no">
    <meta name="keywords" content="假文件,破损文件,不同格式,制定大小,生成,fake,file,generate">
    <meta name="description" content="生成不同格式制定大小的假文件">

    <title>假文件生成器 Generate Corrupt File</title>

    <!-- Compiled and minified CSS -->
    <link rel="stylesheet"
          href="https://cdn.jsdelivr.net/npm/@materializecss/materialize@1.1.0-alpha/dist/css/materialize.min.css">
    <!-- Compiled and minified JavaScript -->
    <script src="https://cdn.jsdelivr.net/npm/@materializecss/materialize@1.1.0-alpha/dist/js/materialize.min.js"></script>
    <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
    <style>
        .tips {
            display: flex;
            padding: 16px 6px;
            border-radius: 4px;

            color: #fff;
            font-weight: 500;
            background-color: #ff9800;
        }
    </style>
</head>
<body>
<nav>
    <div class="nav-wrapper blue">
        <a href="#" class="brand-logo left">Generate Fake File</a>
        <ul id="nav-mobile" class="right">
            <li>
                <a id="share">
                    <i class="material-icons">share</i>
                </a>
            </li>
        </ul>
    </div>
</nav>
<div class="container">
    <!--    <h1 class="center-align blue">破损文件生成器</h1>-->
    <p class="blue-text darken-3">生成特定大小、特定格式的假文件，仅供测试和学习使用。</p>
    <form>
        <div class="row">
            <div class="input-field col s12">
                <select id="extSelect" class="validate">
                    <option value="" disabled selected>选择文件类型</option>
                    <option value="jpg">jpg</option>
                    <option value="jpeg">jpeg</option>
                    <option value="gif">gif</option>
                    <option value="png">png</option>
                    <option value="bmp">bmp</option>
                    <option value="rtf">rtf</option>
                    <option value="pdf">pdf</option>
                    <option value="doc">doc</option>
                    <option value="docx">docx</option>
                    <option value="xls">xls</option>
                    <option value="xlsx">xlsx</option>
                    <option value="ppt">ppt</option>
                    <option value="pptx">pptx</option>
                    <option value="mp3">mp3</option>
                    <option value="mp4">mp4</option>
                    <option value="ogg">ogg</option>
                    <option value="rar">rar</option>
                    <option value="zip">zip</option>
                    <option value="7z">7z</option>
                </select>
                <label for="extSelect">文件类型</label>
            </div>
        </div>
        <div class="row">
            <div class="input-field col s12">
                <input id="filename" type="text" placeholder="请输入文件名" value="fake_file" class="validate" required>
                <label for="filename">文件名</label>
                <a class="btn-floating waves-effect waves-light blue suffix tooltipped" data-position="top"
                   id="randomFileName"
                   data-tooltip="随机文件名"><i class="material-icons">autorenew</i></a>
            </div>
        </div>
        <div class="row">
            <div class="input-field col s6">
                <input id="size" step="1" type="number" min="1" max="9007199254740991" value="3" placeholder="请输入文件大小"
                       required class="validate">
                <label for="size">文件大小</label>
            </div>
            <div class="input-field col s6">
                <select id="unit">
                    <option value="Bytes">Bytes</option>
                    <option value="KB" selected>KB</option>
                    <option value="MB">MB</option>
                    <option value="GB">GB</option>
                </select>
                <label for="unit">单位</label>
            </div>
        </div>
        <div class="row tips-wrapper" hidden>
            <div class="tips z-depth-2">
                <i class="material-icons">new_releases</i>生成过大的文件可能会阻塞浏览器运行。
            </div>
        </div>
        <div class="row center-align">
            <a class="waves-effect blue btn btn-large" id="generateBtn"><i class="material-icons right">done</i>Generate</a>
        </div>
    </form>
</div>
<script>
  document.addEventListener('DOMContentLoaded', function () {
    const elems = document.querySelectorAll('select');
    M.FormSelect.init(elems, {
      // specify options here
    });
    const tooltipElements = document.querySelectorAll('.tooltipped');
    M.Tooltip.init(tooltipElements, {
      // specify options here
    });
  });
</script>
<!--<script>-->
<!--  // const ext = ["jpg", "jpeg", "gif", "png", "bmp", "rtf", "pdf", "doc", "docx", "xls", "xlsx", "ppt", "pptx", "mp3", "mp4", "ogg", "rar", "zip", "7z"];-->
<!--  // const unit = ['Bytes', 'KB', 'MB', 'GB'];-->
<!--  const header = [137, 80, 78, 71, 13, 10, 26, 10];-->
<!--  const rear = [1, 2, 3, 4]-->
<!--  const typedArray = new Int8Array([...header, ...rear]);-->
<!--  // arrayBufferObj.fill(1);-->
<!--  // const bolb = new Blob([typedArray], {type: 'image/png'});-->
<!--  // const url = URL.createObjectURL(bolb);-->
<!--  // console.log(url);-->
<!--  // document.querySelector("#pic").src = url;-->
<!--  // download(bolb);-->
<!--</script>-->
<script>
  const generateBtn = document.getElementById('generateBtn');
  const randomFileNameBtn = document.getElementById('randomFileName');
  const extSelect = document.getElementById('extSelect');
  const filename = document.getElementById('filename');
  const size = document.getElementById('size');
  const unit = document.getElementById('unit');
  const tipsWrapper = document.querySelector('.tips-wrapper');
  const shareBtn = document.getElementById('share');

  generateBtn.addEventListener('click', function (e) {
    e.preventDefault();
    const extValue = extSelect.value;
    const filenameValue = filename.value;
    const sizeValue = size.value;
    const unitValue = unit.value;
    if (!extValue) return M.toast({text: '请选择文件类型'});
    if (!filenameValue) return M.toast({text: '请输入文件名'});
    if (!sizeValue) return M.toast({text: '请输入文件大小'});
    const regExp = /^[1-9]\d*$/g;
    if (!regExp.test(sizeValue)) return M.toast({text: '文件大小应为正整数'});
    spawnFile(filenameValue, extValue, sizeValue, unitValue);
  });

  unit.addEventListener('change', function (e) {
    if (e.target.value === 'GB') {
      tipsWrapper.hidden = false;
    } else {
      tipsWrapper.hidden = true;
    }
  });

  shareBtn.addEventListener('click', () => {
    if(navigator.share){
      navigator.share({
        title: document.title,
        text: '生成特定大小、特定格式的假文件，仅供测试和学习使用。',
        url: location.href
      })
    }
  })

  let randomJSON = null;
  randomFileNameBtn.addEventListener('click', function () {
    if (!randomJSON) {
      fetch('./random.json', {method: 'GET'})
        .then((e) => {
          return e.json();
        })
        .then((data) => {
          randomJSON = data;
          filename.value = randomJSON[Math.floor(Math.random() * 1000)]
        }).catch((e) => {
        console.log(e);
        M.toast({text: e});
      });
    } else {
      filename.value = randomJSON[Math.floor(Math.random() * 1000)]
    }

  });

  const mime = {
    "jpg": "image/jpeg",
    "jpeg": "image/jpeg",
    "gif": "image/gif",
    "png": "image/png",
    "bmp": "image/bmp",
    "rtf": "application/rtf",
    "pdf": "application/pdf",
    "doc": "application/msword",
    "docx": "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
    "xls": "application/vnd.ms-excel",
    "xlsx": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
    "ppt": "application/vnd.ms-powerpoint",
    "pptx": "application/vnd.openxmlformats-officedocument.presentationml.presentation",
    "mp3": "audio/mp3",
    "mp4": "video/mp4",
    "ogg": "audio/ogg",
    // "rar": "application/octet-stream",
    "rar": "application/x-rar-compressed", // unofficial
    "zip": "application/zip",
    "7z": "application/x-7z-compressed"
  }

  function spawnFile(filename, ext, size, unit) {
    const unitSizeFactor = {
      Bytes: 1,
      KB: 1024,
      MB: 1048576,
      GB: 1073741824,
    };
    const typedArray = new Int8Array(size * unitSizeFactor[unit]);
    const bolb = new Blob([typedArray], {type: mime[ext]});
    const url = URL.createObjectURL(bolb);
    const linkElement = document.createElement('a');
    linkElement.href = url;
    linkElement.download = filename + '.' + ext;
    document.documentElement.appendChild(linkElement);
    linkElement.click();
    URL.revokeObjectURL(url);
    document.documentElement.removeChild(linkElement);
  }
</script>
</body>
</html>